<template>
    <view>
        <!-- 固定车位预约表单 -->

        <view>
            <view class="top-card">
                <van-cell-group>
                    <van-cell title="停车场">{{ datas.parkingName }}</van-cell>
                    <van-cell title="营业时间" v-if="datas.openTime">{{ datas.openTime || '24小时' }}</van-cell>
                    <van-cell title="停车要求">{{ datas.parkingRequire == 1 ? '限小区居民' : '对公众开放' }}</van-cell>
                    <van-cell title="车位号">{{ datas.spaceNo }}</van-cell>
                    <van-cell title="车位类型">{{ datas.spaceOwnerType == 1 ? '个人所有' : '企业经营' }}</van-cell>
                    <van-cell center title="共享时间段" :border="false">
                        <view class="card-time1">{{ datas.tempStartTime }} - {{ datas.tempEndTime }}</view>
                        <view class="card-time2">{{ datas.validStartTimeDesc }}-{{ datas.validEndTimeDesc }}, {{ datas.tempCycleDesc }}</view>
                        <!-- <view wx:for="{{filters.split(datas.realTime)}}" wx:key="index">{{item}}</view> -->
                    </van-cell>
                </van-cell-group>
            </view>
            <view class="split-line"></view>
            <view class="top-card">
                <van-cell title="收费信息" :border="false">
                    <view class="fee-tag" v-if="!true">{{ datas.feeRule }}</view>
                    <view class="fee">{{ rules1 }}</view>
                </van-cell>
            </view>
            <view class="split-line"></view>
            <view class="cell-btm">
                <van-cell title="我的车辆" is-link @click="showCarFun">
                    <span :class="carNo != '请选择' ? 'infoText' : ''">{{ carNo }}</span>
                </van-cell>
                <van-cell title="开始停车" is-link @click="showParkFun">
                    <span :class="parkTime != '请选择' ? 'infoText' : ''">{{ parkTime }}</span>
                </van-cell>
            </view>
            <view class="rule">
                <van-checkbox v-model="checked" @change="onChange" checked-color="#00BCAB"></van-checkbox>
                <text @tap="showRule" style="padding-left: 10rpx">我已经阅读并同意《停车服务协议》</text>
            </view>
            <view class="btn" @tap="submit">确定预约</view>
            <view class="tip-btm">
                <view class="tip-title">重要提醒：</view>
                <view class="tip-content">
                    <view>1、如需取消预约，请提前30分钟取消，否则将收取3元/笔手续费。若已超过预约时间再取消，则需要支付预约时间到取消时间这段时间的停车费用。</view>
                    <view>2、准时或提前到达根据车辆实际出入时间段计费。晚于预约时间到达，车主需承担支付预约时间到入场时间这段时间的停车费用。</view>
                    <view>3、若您超过车位主可共享的时间才离开，超时时间段将需要支付2倍的罚金，并且超时3次平台将给予处罚，限制平台功能使用1个月。</view>
                    <view>4、需要修改停车车辆信息，请到个人中心中修改。</view>
                </view>
            </view>
        </view>
        <view>
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">停车服务协议</view>
                    <!-- <view class="rule-content">{{platformRules}}</view> -->
                    <view class="rule-content"><rich-text :nodes="platformRules"></rich-text></view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
        </view>
        <!-- 车辆下拉 -->
        <van-popup v-model="showCar" position="bottom" @close="onCloseCar">
            <van-picker show-toolbar :columns="carList" @confirm="onSelectCar" @cancel="onCloseCar" />
        </van-popup>
        <!-- 时间下拉 -->
        <van-popup v-model="showPark" position="bottom" @close="oncloseParkTime">
            <van-datetime-picker
                type="datetime"
                title="选择开始停车时间"
                v-model="currentDate"
                :min-date="minDate"
                :max-date="maxDate"
                :filter="filter"
                @confirm="SelectDate"
                @cancel="oncloseParkTime"
                :formatter="formatter"
            />
        </van-popup>
        <van-dialog id="van-dialog" />
        <van-toast id="van-toast" />
        <van-dialog
            id="van-dialog2"
            v-model="isShowPayTip"
            title="支付提醒"
            confirm-button-text="去支付"
            cancel-button-text="稍后再看"
            confirm-button-color="#00BCAB"
            cancel-button-color="#AEAEAE"
            v-model-cancel-button="true"
            message="您有订单未支付，请尽快支付"
            @confirm="gotoPay($event, { tagId: 'van-dialog2' })"
        />
    </view>
</template>
<script module="filters" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
// import vanCell from '@vant/weapp/cell/index';
// import vanCellGroup from '@vant/weapp/cell-group/index';
// import vanCheckbox from '@vant/weapp/checkbox/index';
// import vanDatetimePicker from '@vant/weapp/datetime-picker/index';
// import vanPicker from '@vant/weapp/picker/index';
// pages/parkSpaceBooking/parkSpaceBooking.js
import config from './../../utils/config.js';
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import { Dialog,Toast } from 'vant';
// import Toast from '@vant/weapp/toast/toast';
export default {
    components: {
        // vanCell,
        // vanCellGroup,
        // vanCheckbox,
        // vanDatetimePicker,
        // vanPicker
    },
    data() {
        return {
            carNo: '请选择',
            parkTime: '请选择',
            showCar: false,
            showPark: false,
            checked: true,
            showRulePop: false,
            datas: {
                parkingName: '',
                openTime: '',
                parkingRequire: 0,
                spaceNo: '',
                spaceOwnerType: 0,
                tempStartTime: '',
                tempEndTime: '',
                validStartTimeDesc: '',
                validEndTimeDesc: '',
                tempCycleDesc: '',
                feeRule: ''
            },
            rules1: '',
            carList: '',
            minDate: new Date().getTime(),
            maxDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 2).getTime(),
            st1: '',
            st2: '',
            ed1: '',
            ed2: '',
            currentDate: new Date().getTime(),

            filter(type, options) {
                if (type === 'minute') {
                    return options.filter((option) => option % 15 === 0);
                }

                return options;
            },

            platformRules: config.platformRules,

            formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`;
                }

                if (type === 'month') {
                    return `${value}月`;
                }

                if (type === 'day') {
                    return `${value}日`;
                }

                if (type === 'hour') {
                    return `${value}时`;
                }

                if (type === 'minute') {
                    return `${value}分`;
                }

                return value;
            },

            isShowPayTip: false,
            gotopayType: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const param = JSON.parse(decodeURIComponent(options.param));
        this.setData({
            datas: param,
            rules1: param.rules1,
            carList: uni.getStorageSync('plateNos').split(','),
            carNo: uni.getStorageSync('plateNos').split(',')[0]
        });
        const startTime = param.startTime.split(',');

        if (startTime.length > 1 && util.zhuanhuan(startTime[0]) > util.zhuanhuan(startTime[1])) {
            startTime.reverse();
        }

        const endTime = param.endTime.split(',');

        if (endTime.length > 1 && util.zhuanhuan(endTime[0]) > util.zhuanhuan(endTime[1])) {
            endTime.reverse();
        }

        var date = new Date(); //1. js获取当前时间

        var min = date.getMinutes(); //2. 获取当前分钟

        date.setMinutes(min + 1); //  let afterMin = new Date().getMinutes()

        this.setData({
            minDate: new Date().getTime() > util.zhuanhuan(startTime[0]) ? new Date().getTime() : util.zhuanhuan(startTime[0]),
            maxDate: util.zhuanhuan(endTime[endTime.length - 1]),
            currentDate: new Date().getTime() > util.zhuanhuan(startTime[0]) ? date.getTime() : util.zhuanhuan(startTime[0]),
            st1: util.zhuanhuan(startTime[0]),
            ed1: util.zhuanhuan(endTime[0]),
            st2: startTime[1] ? util.zhuanhuan(startTime[1]) : util.zhuanhuan(startTime[0]),
            ed2: endTime[1] ? util.zhuanhuan(endTime[1]) : util.zhuanhuan(endTime[0])
        });
        this.setData({
            parkTime: util.getDate(this.currentDate, 'yyyy-MM-dd hh:mm:ss')
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
        onChange(event) {
            this.setData({
                checked: event.detail
            });
        },

        submit() {
            if (this.carNo == '请选择') {
                uni.showToast({
                    title: '请选择车辆',
                    icon: 'none'
                });
                return;
            }

            if (this.parkTime == '请选择') {
				uni.showToast({
				    title: '请选择开始停车时间',
				    icon: 'none'
				});
                return;
            }

            if (this.checked == false) {
				uni.showToast({
				    title: '请勾选同意《停车服务协议》',
				    icon: 'none'
				});
                return;
            }

            let param = {
                unionId: uni.getStorageSync('unionId'),
                startTime: this.parkTime,
                spaceNo: this.datas.spaceNo,
                parkingCode: this.datas.parkingCode,
                plateNo: this.carNo,
                manageId: this.datas.manageId,
                rentedType: '1'
            };
            uni.showLoading({
                title: '加载中'
            });
            util.request(api.parkSpaceBook, param, 'POST')
                .then((res) => {
                    uni.hideLoading();

                    if (res.success) {
                        uni.requestSubscribeMessage({
                            tmplIds: ['_Gn5a0g0ID4N101EWPWO198A2fOgq6BLsY4zdD4MN70', 'VzATjR4VJmNaFOkdBHo4BhVS1EgGvyE75FJtsSG5zfs', 'HQAZBgxWjaryrdb_-FUYpka6-t0R49M-NPd4-GYmMzM'],

                            success(sus) {
                                uni.showToast({
                                    title: '预约成功',
                                    icon: 'success'
                                });
                                uni.navigateTo({
                                    url: '../rentSuccess/rentSuccess?from=0'
                                });
                            },

                            fail(err) {
                                uni.showToast({
                                    title: '预约成功',
                                    icon: 'success'
                                });
                                uni.navigateTo({
                                    url: '../rentSuccess/rentSuccess?from=0'
                                });
                            }
                        });
                    } else if (res.busiCode == 'waitingToPay1') {
                        this.setData({
                            gotopayType: 1,
                            isShowPayTip: true
                        });
                    } else if (res.busiCode == 'waitingToPay2') {
                        this.setData({
                            gotopayType: 2,
                            isShowPayTip: true
                        });
                    } else {
                        Dialog.alert({
                            message: res.msg || '预约失败，请重试',
                            confirmButtonText: '我知道了'
                        }).then(() => {
                            // on close
                        });
                    }
                })
                .catch((err) => {
                    Toast(err || '接口出错了，请重试');
                });
        },

        /**
         * 选择停车时间
         */
        SelectDate(e) {
            if (e.detail > this.ed1 && e.detail < this.st2) {
                Toast('不在该车位可停时间范围内，请重新选择！');
            } else if (e.detail <= new Date().getTime()) {
                Toast('请滑动选择时间！');
            } else {
                this.setData({
                    showPark: false,
                    parkTime: util.getDate(e.detail, 'yyyy-MM-dd hh:mm:ss')
                });
            }
        },

        /**
         * 选择停车车辆
         */
        onSelectCar(e) {
            this.setData({
                carNo: e.detail.value,
                showCar: false
            });
        },

        showCarFun() {
            this.setData({
                showCar: true
            });
        },

        showParkFun() {
            this.setData({
                showPark: true
            });
        },

        showRule() {
            this.setData({
                showRulePop: true
            });
        },

        closeRule() {
            this.setData({
                showRulePop: false,
                checked: true
            });
        },

        onCloseCar() {
            this.setData({
                showCar: false
            });
        },

        oncloseParkTime() {
            this.setData({
                showPark: false
            });
        },

        /**跳转支付 */
        gotoPay(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            uni.navigateTo({
                url: '../order/index?type=' + this.gotopayType
            });
        }
    }
};
</script>
<style>
@import './parkSpaceBooking.css';
</style>
